package com.dhcc.core.framework.mybatisplus;

import java.util.Date;

import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.dhcc.core.api.shiro.ApiShiroKit;
import com.dhcc.core.framework.security.ShiroKit;
import com.dhcc.core.modules.system.entity.User;

/**
 * mybatisplus自定义填充公共字段 ,即没有传的字段自动填充
 * 
 * @ClassName: MetaObjectHandler
 * @Description: TODO
 * @author: cyf
 * @date: 2018年3月8日 下午4:56:59
 */
@Component
public class MetaObjectHandler extends com.baomidou.mybatisplus.mapper.MetaObjectHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    // 新增填充
    @Override
    public void insertFill(MetaObject metaObject) {
        logger.info("正在调用该insert填充字段方法");
        if (metaObject.hasGetter("createDate")) {
            Object createDate = getFieldValByName("createDate", metaObject);
            if(null == createDate){
                setFieldValByName("createDate", new Date(), metaObject);
            }
        }
        if(metaObject.hasGetter("createBy")){
            Object createBy = getFieldValByName("createBy", metaObject);
            if (null == createBy) {
                User user = ApiShiroKit.getUser();
                if (user == null) {
                    user = ShiroKit.getUser();
                }
                if (user != null) {
                    setFieldValByName("createBy", user.getId(), metaObject);
                }
            }
        }
    }

    // 更新填充
    @Override
    public void updateFill(MetaObject metaObject) {
        logger.info("正在调用该update填充字段方法");
        if (metaObject.hasGetter("updateDate")) {
            setFieldValByName("updateDate", new Date(), metaObject);
        }
        if(metaObject.hasGetter("updateBy")){
            User user = ApiShiroKit.getUser();
            if (user == null) {
                user = ShiroKit.getUser();
            }
            if (user != null) {
                setFieldValByName("updateBy", user.getId(), metaObject);
            }
        }
    }
}
